package org.origin.centre.security.point;

import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 客户端信息异常类重写处理
 *
 * @author ferret
 * @version 2024-05-08
 */
@SuppressWarnings("unused")
public class IBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
    private final boolean isResultOk;

    public IBasicAuthenticationEntryPoint(boolean isResultOk) {
        this.isResultOk = isResultOk;
        this.setRealmName("/oauth/token");
    }

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        this.responseError(response, HttpStatus.INTERNAL_SERVER_ERROR, "客户端信息不存在或不可用");
    }

    /**
     * 响应信息
     *
     * @param response 请求响应
     * @param status   响应状态
     * @throws IOException 异常
     */
    @SuppressWarnings("SameParameterValue")
    protected void responseError(HttpServletResponse response, HttpStatus status, String message) throws IOException {
        response.setStatus(this.isResultOk ? HttpStatus.OK.value() : status.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(String.format("{\"status\":%d,\"message\":\"%s\"}", status.value(), message));
    }
}
